package com.me.Utils;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ServUtil {
	private static Properties props = new Properties();

	static {
		try {
			InputStream in = ServUtil.class.getClassLoader().getResourceAsStream("config.properties");
			props.load(in);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static String getProperty(String key) {
		return props.getProperty(key);
	}

	/**
	 * 使用正则表达式比对State，如果匹配返回原字符串，否则返回Null
	 * @param state
	 * @param regex
	 * @return
	 */
	public static String getRegState(String state, String regex) {
		if (regex == null || regex == "") return null;
		Pattern p = Pattern.compile(regex);
		Matcher m = p.matcher(state);
		if (m.matches()) {
			return state.substring(state.lastIndexOf(".") + 1);
		}
		return null;
	}

	/**
	 * 解析请求的状态，如果是多字节使用getReq
	 * @param req
	 * @return
	 */
	public static void parseParam(HttpServletRequest req){
		if (req.getParameterMap().size() > 0) return;
		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setSizeThreshold(20 * 1024 * 1024);
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setHeaderEncoding("UTF-8");
		upload.setSizeMax(-1);
		try {
			List<FileItem> items = upload.parseRequest(req);
			req.setAttribute("items",items);
		} catch (FileUploadException e) {
			e.printStackTrace();
		}
	}

	public static String writeResource(FileItem item,String path)  {
		try {
			if (item == null || item.getName() == "") return "";
 			File file = new File(path);
			if (!file.exists() && !file.isDirectory()) {
				file.mkdir();
			}
			Date date = new Date();
			String fileName = date.hashCode() + item.getName().substring(item.getName().lastIndexOf("."));
			String fullName = path + "/" + fileName;

			InputStream in = item.getInputStream();
			FileOutputStream out = new FileOutputStream(fullName);
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = in.read(buffer)) > 0) {
				out.write(buffer, 0, len);
			}
			in.close();
			out.close();
			item.delete();
			return "/img/upload/" + fileName;
		} catch (IOException e) {
			e.printStackTrace();
		}

		return "error";
	}

}

